import {Plugin} from "@ckeditor/ckeditor5-core";
import {FileDialogButtonView} from "@ckeditor/ckeditor5-upload";
import mediaIcon from '@ckeditor/ckeditor5-media-embed/theme/icons/media.svg';

export default class UploadVideoUI extends Plugin {
    /**
     * @inheritDoc
     */
    static get pluginName() {
        return 'UploadVideoUI'
    }

    /**
     * @inheritDoc
     */
    init() {
        const editor = this.editor;
        editor.ui.componentFactory.add('uploadVideo', (locale) => {
            const view = new FileDialogButtonView(locale);
            const command = editor.commands.get('insertVideo');

            view.set({
                acceptedType: 'video/mp4',
                allowMultipleFiles: false
            });

            view.buttonView.set({
                icon: mediaIcon,
                label: editor.t('Insert video'),
                tooltip: true
            });

            view.buttonView.bind("isEnabled").to(command);

            view.on('done', (evt, files) => {
                if (window.AdminUploadAdapter) {
                    (new window.AdminUploadAdapter()).upload(files, function (url) {
                        editor.execute('insertVideo', url);
                    });
                } else {
                    editor.execute('insertVideo', URL.createObjectURL(files[0]));
                }
            });

            return view;
        });
    }
}